package com.example.shixun.config;

import com.example.shixun.pojo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


/**
 * 定义登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 该方法在请求到达控制器处理器之前，执行，返回值为true代表继续向下执行，
     * 返回值为false，中断后续操作
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       Object  user=request.getSession().getAttribute("user");
       if(user==null){
           PrintWriter pw= response.getWriter();
           response.setCharacterEncoding("UTF-8");
           response.setContentType("text/html;charset=utf-8");
           ObjectMapper mapper=new ObjectMapper();
           pw.write(mapper.writeValueAsString(Result.fail(100,"please login")));
          // request.getRequestDispatcher("/index.html").forward(request,response);
           return false;
       }else{

           return true;
       }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
